﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Site_Extractor
{
    public class RssLink
    {
        private static string xItem = "item", xTitle = "title", xLink = "link";
        public static List<RssLink> GetLinks(string url)
        {
            List<RssLink> links = new List<RssLink>();
            string link = url;
            XmlReader reader = XmlReader.Create(link);
            while (!reader.EOF)
            {
                try
                {
                    reader.Read();
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name == xTitle) reader.Skip();
                        if (reader.Name == xItem)
                        {
                            RssLink l = ParseFeed(reader.ReadSubtree());
                            if (null != l)
                                links.Add(l);
                            reader.Skip();
                        }
						if (reader.Name == xTitle) reader.Skip();
                    }					
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: {0}", e.Message);
                }
            }
            return links;
        }

        

        private static RssLink ParseFeed(XmlReader xmlReader)
        {
            string link = null, desc = null;
            while (!xmlReader.EOF)
            {
                if (xmlReader.NodeType == XmlNodeType.Element)
                {
                    if (xmlReader.Name == xTitle) desc = xmlReader.ReadElementContentAsString();
                    if (xmlReader.Name == xLink) link = xmlReader.ReadElementContentAsString();
                }
                xmlReader.Read();
            }
            if (null == link) return null;
            return new RssLink(link, desc);
        }

        public string Link;
        public string Description;
        public RssLink(string lnk, string desc) { this.Link = lnk; this.Description = desc; }
        public override string ToString()
        {
            return Description;
        }
    }
	
}
